<script setup lang="ts">
import { ref, onMounted, inject } from 'vue'
import Home from './views/Home/Home.vue'
import { getUrlParams } from './utils'
import { useIframeTargetOrigin } from '@/composables/useIframeTargetOrigin'
import type { ApplicationIframeSDKManager } from '@/plugins/iframeSDKManager/iframeSDKManager.d'
import { IframeSDKEventMap } from '@/plugins/iframeSDKManager/events'
import CoverLoading from './components/common/CoverLoading/CoverLoading.vue'
import { showFailToast } from 'vant'
import useSceneDataStore from '@/stores/scene'

const iframeSrc = ref('')
const { getTargetOrigin } = useIframeTargetOrigin()
const APP_KEY: string = import.meta.env.VITE_APP_KEY
const iframeSDKManager = inject('iframeSDKManager') as ApplicationIframeSDKManager
const homeRef = ref<InstanceType<typeof Home>>()

// 首次进入的全局loading
const coverLoading = ref(true)

const sceneDataStore = useSceneDataStore()
const { setBusinessParams } = sceneDataStore

// http://localhost:10081/?work_id=KLSgEGFpqqb

onMounted(() => {
  const workId: string = getUrlParams(window.location.href, 'work_id') || ''

  // 首次进入时url上传递的project_id
  const initProjectId: string = getUrlParams(window.location.href, 'project_id') as string

  if (initProjectId) {
    setBusinessParams({
      project_id: initProjectId
    })
  }

  if (!workId) {
    // 全局提示
    coverLoading.value = false

    showFailToast({
      message: '未找到作品',
      duration: 20000,
      icon: 'clear'
    })

    return
  }

  const targetOrigin: string = getTargetOrigin()
  const qverseIframe = document.querySelector('#qverse-iframe') as HTMLIFrameElement

  // 初始化MessageSDK
  iframeSDKManager.init({
    targetWindow: qverseIframe,
    targetOrigin: targetOrigin,
    config: {
      hide_ui: ['all'], // 隐藏全部元素
      hide_loading: 'on' // 隐藏loading
    }
  })

  // 监听作品加载完成消息， 完成后关闭全局loading
  iframeSDKManager.on(IframeSDKEventMap.WORK_LOADED, () => {
    coverLoading.value = false
  })

  // 再设置目标地址
  if (ENV_MODE === 'localdev') {
    iframeSrc.value = `${targetOrigin}/?appKey=${APP_KEY}&work_id=${workId}`
  } else {
    iframeSrc.value = `${targetOrigin}/qverse/work/${workId}?appKey=${APP_KEY}`
  }

  qverseIframe.onload = () => {
    iframeSDKManager.emit('iframe.loaded', {})
  }
})
</script>
<template>
  <div class="app-container">
    <!-- 众趣作品iframe容器dom -->
    <iframe id="qverse-iframe" :src="iframeSrc" frameborder="0" class="qverse-iframe"></iframe>
    <!-- 自定义业务组件 -->
    <Home ref="homeRef" />
    <!-- 全局遮罩 -->
    <CoverLoading :show="coverLoading" />
  </div>
</template>

<style>
.qverse-iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: none;
  z-index: 0;
}
</style>
